<template>
  <div class="vueEditor">
    <!-- 使用自定义图片上传 -->
    <input
      :ref="inputRef"
      type="file"
      name="img"
      accept="image/jpeg,image/jpg,image/png"
      id="quillInput"
      class="quill-img"
      multiple="multiple"
      hidden
      @change="getImgUrl($event)"
    />
    <quill-editor
      :ref="toEditorRef"
      :options="editorOption"
      @ready="onEditorReady($event)"
      v-model="content"
      @change="onEditorChange(toEditorRef)"
      @blur="onEditorBlur($event, toEditorRef)"
      @focus="onEditorFocus($event, toEditorRef)"
    ></quill-editor>
  </div>
</template>

<script>
import Quill from "quill";
import { quillEditor } from "vue-quill-editor";
import ImageResize from "quill-image-resize-module";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
// import "quill/dist/quill.core.css";
// import "quill/dist/quill.snow.css";
// import "quill/dist/quill.bubble.css";
Quill.register("modules/imageResize", ImageResize);
Quill.register("modules/ImageExtend", ImageExtend);
// import {config} from '@/base/base-config'

const fonts = [
  "SimSun",
  "SimHei",
  "Microsoft-YaHei",
  "KaiTi",
  "FangSong",
  "Arial",
  "Times-New-Roman",
  "sans-serif",
];
const sizes = [
  "12px",
  false,
  "16px",
  "18px",
  "20px",
  "25px",
  "30px",
  "35px",
  "40px",
  "50px",
  "60px",
  "80px",
  "100px",
];
const lineHeights = [
  "1",
  "1.1",
  "1.2",
  "1.3",
  "1.4",
  "1.5",
  "1.6",
  "1.8",
  "2",
  "3",
  "4",
  "5",
];
const Size = Quill.import("formats/size");
const Font = Quill.import("formats/font");
Size.whitelist = sizes;
Font.whitelist = fonts;
Quill.register(Size, true);
Quill.register(Font, true);

let Parchment = Quill.import("parchment");

class lineHeightAttributor extends Parchment.Attributor.Style {}

const lineHeightStyle = new lineHeightAttributor("lineHeight", "line-height", {
  scope: Parchment.Scope.INLINE,
  whitelist: lineHeights,
});
Quill.register({ "formats/lineHeight": lineHeightStyle }, true);

export default {
  name: "vueEditor",
  props: {
    editorContent: {
      type: String,
      default: "",
    },
    /* input 的ref值 */
    inputRef: {
      type: String,
      default: "quillInput",
    },
    /* quill-editor 的ref值 */
    toEditorRef: {
      type: String,
      default: "quillEditor",
    },
    myConfig: {
      type: Object,
      default: () => {},
    },
    action: {
      type: String,
      default: "",
    },
  },
  data: function () {
    return {
      quill: null,
      content: "",
      editorOption: {
        theme: "snow",
        modules: {
          clipboard: {
            // 粘贴版，处理粘贴时候的自带样式
            matchers: [[Node.ELEMENT_NODE, this.HandleCustomMatcher]],
          },
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false,
          },
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
          ImageExtend: {
            loading: false,
            // 如果不作设置，即{}  则依然开启复制粘贴功能且以base64插入
            name: "file", // 图片参数名
            size: 10, // 可选参数 图片大小，单位为M，1M = 1024kb
            action: this.action, // 服务器地址, 如果action为空，则采用base64插入图片
            // response 为一个函数用来获取服务器返回的具体图片地址
            // 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
            // 则 return res.data.url
            response: (res) => {
              if (res.success) {
                return res.data;
              } else {
                this.$message.error(res.msg);
                return false;
              }
              // return res;
            },
            headers: (xhr) => {
              xhr.setRequestHeader("Authorization", window._token);
            }, // 可选参数 设置请求头部
            sizeError: () => {
              this.$message.warning("图片最大不能超过10M");
            }, // 图片超过大小的回调
            start: () => {
            }, // 可选参数 自定义开始上传触发事件
            end: () => {
            }, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
            error: () => {
              this.$message.warning("图片上传失败");
            }, // 可选参数 上传失败触发的事件
            success: () => {
            }, // 可选参数  上传成功触发的事件
            change: (xhr, formData) => {
              // formData.append('token', 'myToken')
              // xhr.setRequestHeader('myHeader','myValue')
              formData.append("fileType", 1);
              formData.append("oldPath", "");
            }, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
          },
          toolbar: {
            container: [
              /*  [{size: sizes}],
							[{font: fonts}],
							[{color: []}, {background: []}],
							[{align: []}],
							['bold', 'italic', 'underline', 'strike'],
							['clean'],
							['link'],
							[{direction: 'rtl'}],
							[{header: [1, 2, 3, 4, 5, 6, false]}],*/
              [{ size: sizes }],
              [{ font: fonts }],
              [{ color: [] }, { background: [] }],
              [{ align: [] }],
              ["italic", "underline", "strike"],
              ["clean"],
              // ['link'],
              // [{direction: 'rtl'}],
              // [{ header: [1, 2, 3, 4, 5, 6, false] }],
              ["image"],
            ], // container为工具栏，此次引入了全部工具栏，也可自行配置

            handlers: {
              // 如果不上传图片到服务器，此处不必配置
              image: (value) => {
                // 劫持原来的图片点击按钮事件
                // QuillWatch.emit(this.quill.id);
                if (value) {
                  //通过input的ref动态获取
                  this.$refs[this.inputRef].click();
                  // // 触发input框选择图片文件
                  // document.querySelector(".avatar-uploader-btn input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
        placeholder: "请输入",
      },
    };
  },
  components: {
    quillEditor,
  },
  watch: {
    myConfig(val) {
      this.editorOption = val;
    },
    editorContent(val) {
      document.querySelector(".ql-editor").innerHTML = val;
    },
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },
  created() {
  },
  mounted() {},
  methods: {
    //聚焦事件  可删除
    onEditorFocus(e, ref) {},
    //失焦事件 可删除
    onEditorBlur(e, ref) {},
    onEditorChange(toref) {
      //触发父组件 修改父组件的值
      this.$emit("input", this.content, toref);
    },
    ready(editorInstance) {
      this.UE = editorInstance;
    },
    HandleCustomMatcher(node, Delta) {
      if (node.src && node.src.indexOf("data:image/png") > -1) {
        Delta.ops = [];
        return Delta;
      }
      let ops = [];
      Delta.ops.forEach((op) => {
        if (op.insert && typeof op.insert === "string") {
          ops.push({
            insert: op.insert,
          });
        } else if (op.insert && typeof op.insert.image === "string") {
          ops.push({
            insert: op.insert,
          });
        }
      });
      Delta.ops = ops;
      return Delta;
    },
    onEditorReady(quill) {
      this.quill = quill;
    },
    toPreview() {
      return document.querySelector(".ql-editor").innerHTML;
    },

    getImgUrl(e) {
      e.stopPropagation();
      if (e.target.files.length > 0) {
        let quill = this.$refs[this.toEditorRef].quill; //获取对应的quill对象
        var reader = new FileReader();
        reader.readAsDataURL(e.target.files[0]);
        reader.onload = function (e) {
          var obj = {
            imgData: e.target.result, //给后台传的参数 base64格式的img参数
          };
          // findList.uploadImage(qs.stringify(obj)).then((data) => {
          //   if (data.ResultCode == 1) {
          // 获取光标所在位置
          let length = quill.getSelection(true).index;
          // 插入图片  res.info为服务器返回的图片地址
          quill.insertEmbed(length, "image", obj.imgData.indexOf("data:image/png") !== -1 ? obj.imgData.replace("data:image/png", "data:image/jpg") : obj.imgData);
          // 调整光标到最后
          quill.setSelection(length + 1);
          //   } else {
          //     this.$message({
          //       message: "图片上传失败!",
          //       type: "error",
          //     });
          //   }
          // });
        };
        this.$refs[this.inputRef].value = null;
        // this.getMultipleUrl(e.target.files); //多文件上传
      }
    },
  },
};
</script>
<style scoped lang="less">
//@import '@/theme/theme-default.scss';

::v-deep .avatar-uploader {
  height: 0;
}
.vueEditor {
  //.editor-btn {
  //  margin-top: 15px;
  //  color: $--color-header-text;
  //  background-color: $--color-header-bg;
  //  border-color: $--color-header-bg;
  //}
  ::v-deep .ql-toolbar.ql-snow .ql-picker-label {
    position: absolute;
    top: -2px;
  }
  ::v-deep .ql-toolbar.ql-snow .ql-font,
  ::v-deep .ql-toolbar.ql-snow .ql-header,
  ::v-deep .ql-toolbar.ql-snow .ql-size {
    .ql-picker-label {
      color: white;
      line-height: 24px;
      position: absolute;
      top: -3px;
    }
  }

  ::v-deep .ql-editor {
    line-height: 1 !important;
    min-height: 82px;
    max-height: 400px;
  }
}
</style>
